<template>
  <header v-if="windowWidth > 992">
    <div class="max-1200 u-flex u-row-between u-flex-wrap">
      <div class="left u-flex">
        <img :src="isHttp(logo)" alt="" class="logo"/>
      </div>
      <div class="right">
        <div id="language-toggle">
          <a href="#" class="language" id="language-link" @click.prevent="toggleLanguage"
             :class="{ chinese: globalLanguage.languageSuffix === 'Ra' }">
            {{ globalLanguage.languageSuffix === 'Cn' ? 'Русский язык' : '中文' }}
          </a>
        </div>
        <div class="tel">
          {{ globalLanguage.languageSuffix === "Cn" ? "全国统一服务电话热线：" : "TEL：" }}
          <span class="tel-text">{{ tel }}</span>
        </div>
      </div>
    </div>
    <div class="nav">
      <div class="max-1200 u-flex">
        <el-menu mode="horizontal" :router="true" :ellipsis="false" active-text-color="#fe7446">
          <template v-for="item in navList" :key="item.id">
            <el-sub-menu
                v-if="item.children && item.children.length"
                :index="item.router"
                :class="{ active: activeItem === item.id }"
                @click="setActive(item.id)"
            >
              <template #title>
                <span class="tit">{{ item["name" + language] }}</span>
              </template>
              <template v-for="subItem in item.children" :key="subItem.id">
                <el-sub-menu
                    v-if="subItem.children && subItem.children.length"
                    :index="subItem.router"
                    :class="{ active: activeItem === subItem.id }"
                    @click="setActive(subItem.id)"
                >
                  <template #title>
                        <span class="tit">{{ subItem["name" + language] }}</span
                        >
                  </template>
                  <template
                      v-for="subSubItem in subItem.children"
                      :key="subSubItem.id"
                  >
                    <el-menu-item :index="subSubItem.router" class="item" @click="setActive(item.id)">
                      <span class="tit">{{ subSubItem["name" + language] }}</span>
                    </el-menu-item>
                  </template>
                </el-sub-menu>
                <el-menu-item v-else :index="subItem.router" @click="setActive(item.id)">
                  <span class="tit">{{ subItem["name" + language] }}</span>
                </el-menu-item>
              </template>
            </el-sub-menu>
            <el-menu-item v-else :index="item.router? item.router : '/'">
              <span>{{ item["name" + language] }}</span>
            </el-menu-item>
          </template>
        </el-menu>
      </div>
    </div>
  </header>
  <el-header v-else-if="windowWidth <= 992">
    <!-- 顶部导航栏 -->
    <navbar style="border-bottom: 1px solid #eee">
      <template v-slot:left>
        <img
            :src="isHttp(logo)"
            alt="logo" id="logo" @click="rehome"/>
      </template>
      <template v-slot:default>
        <!--            {{$store.state.isChinese ? 'Russian' : 'Chinese' }}-->
        <span @click="toggleLanguage">{{ globalLanguage.languageSuffix === "Cn" ? "Russian" : "Chinese" }}</span>
      </template>
      <template v-slot:right>
        <div>
          <!-- 点击时候转换图标，并弹出菜单 -->
          <i :class="iconClass" @click="menu"></i>
        </div>
      </template>
    </navbar>
    <div class="menu-container" :class="{ show: isMenuVisible }">
      <el-col :span="12" style="max-width: 100%">
        <el-menu
            :default-active="activeIndex"
            class="el-menu-vertical-demo"
            @open="handleOpen"
            @close="handleClose"
            style="width: 100%"
            :router="true"
        >
          <template v-for="item in navList" :key="item.id">
            <el-sub-menu v-if="item.children && item.children.length" :index="item.router">
              <template #title>
                <span>{{ globalLanguage.languageSuffix === "Cn" ? item.nameCn : item.nameRa }}</span>
              </template>
              <template v-for="subItem in item.children" :key="subItem.id">
                <el-sub-menu v-if="subItem.children && subItem.children.length" :index="subItem.router">
                  <template #title>
                    <span>{{ globalLanguage.languageSuffix === "Cn" ? subItem.nameCn : subItem.nameRa }}</span>
                  </template>
                  <template v-for="subSubItem in subItem.children" :key="subSubItem.id">
                    <el-menu-item :index="subSubItem.router" class="item">
                      <div @click="menu" style="width: 100%; text-align: left">
                        {{ globalLanguage.languageSuffix === "Cn" ? subSubItem.nameCn : subSubItem.nameRa }}
                      </div>
                    </el-menu-item>
                  </template>
                </el-sub-menu>
                <el-menu-item v-else :index="subItem.router">
                  <div @click="menu" style="width: 100%; text-align: left">
                    {{ globalLanguage.languageSuffix === "Cn" ? subItem.nameCn : subItem.nameRa }}
                  </div>
                </el-menu-item>
              </template>
            </el-sub-menu>
            <el-menu-item v-else :index="item.router? item.router : '/'">
              <router-link :to="item.router" @click="menu" style="width: 100%; text-align: left">
                {{ globalLanguage.languageSuffix === "Cn" ? item.nameCn : item.nameRa }}
              </router-link>
            </el-menu-item>
          </template>
        </el-menu>
      </el-col>
    </div>
  </el-header>
</template>

<script setup>
import "@/assets/css/homeview.css"
import navbar from "@/nav/navbar.vue";
import "../index.css"; // 引入头部样式文件
import {ref, onMounted, getCurrentInstance, onUnmounted, computed} from "vue";
import axios from "axios";
import {useRoute} from 'vue-router';

const route = useRoute();
import {ElMessage} from 'element-plus'
import {listNavMenu, findOneConfigs, updateNavMenu, finconfigmap, updateConfigMap} from "@/api/index.js";
import {islocahost} from "@/utils/index.js";
import component from "element-plus/es/components/tree-select/src/tree-select-option";
// 获取Vue实例的全局属性中的语言相关对象
const globalLanguage = getCurrentInstance().appContext.config.globalProperties.globalLanguage;
const navList = ref([]);
const isChinese = ref(true); // 用于切换语言，默认为中文
const dialogVisible = ref(false)
const language = ref(globalLanguage.languageSuffix);
const isHttp = getCurrentInstance().appContext.config.globalProperties.isHttp;
const logo = ref();
const tel = ref();
const telId = ref();
const activeItem = ref(null); // 跟踪当前激活菜单项
const fileList = ref([]); // 用于存储上传的文件列表
const baseUrl = getCurrentInstance().appContext.config.globalProperties.baseUrl;
const apiUrl = ref(import.meta.env.VITE_APP_BASE_API);
const windowWidth = ref(window.innerWidth); // 用于判断当前窗口宽度
const showAddMenu = ref(false); // 控制添加菜单项输入框的显示
const newMenuItemName = ref(''); // 绑定输入框的值
const isMenuOpen = ref(false); // 控制菜单的显示状态
const iconClass = computed(() => {
  return isMenuOpen.value ? "iconfont icon-guanbi" : "iconfont icon-xiangqing";
});
const isMenuVisible = computed(() => {
  return isMenuOpen.value; // 当isMenuOpen为true时，显示菜单容器
});
const activeIndex = computed(() => {
  return route.path;
});
const handleResize = () => {
  windowWidth.value = window.innerWidth;
};
onMounted(() => {
  // 初始化 windowWidth
  windowWidth.value = window.innerWidth;
  window.addEventListener('resize', handleResize);
});

onUnmounted(() => {
  window.removeEventListener('resize', handleResize);
});
// 隐藏添加菜单项的输入框，并重置输入值
const cancelAddMenu = () => {
  showAddMenu.value = false;
  newMenuItemName.value = '';
};
//点击图标切换状态
const menu = () => {
  isMenuOpen.value = !isMenuOpen.value;
};
const rehome = () => {
  if (isMenuOpen.value) {
    menu();
  }
};
const toggleLanguage = () => {
  // 切换语言
  globalLanguage.languageSuffix = globalLanguage.languageSuffix === "Cn" ? "Ra" : "Cn";
  language.value = globalLanguage.languageSuffix;
};

const handleOpen = (key, keyPath) => {
  console.log("open", key, keyPath);
};
const handleClose = (key, keyPath) => {
  console.log("close", key, keyPath);
};


// 添加新菜单项
const addMenu = () => {
  if (newMenuItemName.value.trim()) {
    const newMenuItem = {
      id: Date.now().toString(), // 使用时间戳作为唯一 ID
      name: newMenuItemName.value,
      children: []
    };
    navList.value.push(newMenuItem); // 将新菜单项添加到 navList
    updateNavList(); // 更新导航列表
    cancelAddMenu(); // 隐藏输入框并重置输入值
  } else {
    // 可以在这里添加提示，告知用户必须输入菜单名称
  }
};


// 定义异步获取数据的函数
const fetchData = async () => {
  try {
    const response = await listNavMenu();
    const data = await findOneConfigs();
    const configmap = await finconfigmap();
    console.log("configmap", configmap);
    console.log("logo", configmap);
    logo.value = configmap.configMapList[0].v; // 获取网站图标
    tel.value = configmap.configMapList[1].v; // 获取网站电话
    telId.value = configmap.configMapList[1].id; // 获取网站电话信息
    navList.value = response.navList; // 获取导航列表
  } catch (error) {
    console.error("获取数据失败:", error);
  }
  const linkElement = document.querySelector("link[rel='icon']");

  if (linkElement) {
    linkElement.href = isHttp(logo.value);
  } else {
    console.error("Link element with rel='icon' not found.");
  }
};
// 将嵌套的菜单列表平展化为一维列表
const flattenMenus = (menus) => {
  const flatList = [];

  const flatten = (menuItems) => {
    menuItems.forEach(item => {
      flatList.push(item);
      if (item.children && item.children.length > 0) {
        flatten(item.children);
      }
    });
  };
  flatten(menus);
  return flatList;
};
// 修改导航菜单的方法
const updateNavList = async () => {
  try {
    const flatNavList = flattenMenus(navList.value);
    console.log(flatNavList);  // 查看平展化的菜单项
    const response = await updateNavMenu(flatNavList);
    alert("导航菜单更新成功！");
  } catch (error) {
    console.error("更新数据失败:", error);
    alert("更新数据失败，请重试！");
  }
};
//上传成功后回调
const handleSuccess = (response, file) => {
  console.log('上传成功的响应:', response);
  console.log('上传的文件信息:', file); // 查看文件信息
  if (response && response.url) {
    logo.value = response.url; // 更新logo为上传成功的图片URL
    console.log('更新后的logo:', logo.value); // 查看更新后的logo
  }
};
// 在上传前检查文件的有效性
const beforeUpload = (file) => {
  console.log('准备上传的文件:', file); // 输出文件信息
  const isImage = file.type.startsWith('image/');
  console.log('是否是图片文件:', isImage);
  if (!isImage) {
    console.log('只能上传图片文件！');
    this.$message.error('上传的文件必须是图片！');
    return false; // 阻止上传
  }
  return true; // 继续上传
};
// 更新电话号码的方法
const updataTel = async () => {
  try {
    const telINfo = {
      id: telId.value,
      v: tel.value,
    };
    console.log("更新电话号码信息:", telINfo);
    const response = await updateConfigMap(telINfo);
    if (response.code === 200) {
      ElMessage.success('修改电话号码成功');
      //刷新页面
      fetchData();
    } else {
      ElMessage.error('修改电话号码失败');
    }


  } catch (error) {
    console.error("更新数据失败:", error);
    alert("更新数据失败，请重试！");
  }
};
const setActive = (id) => {
  activeItem.value = id; // 设置激活的菜单项
};
// 在组件挂载时调用 fetchData
onMounted(() => {
  fetchData();
});
/*document.addEventListener("DOMContentLoaded", function () {
  const languageLink = document.getElementById("language-link");
  // @ts-ignore
  languageLink.addEventListener("click", function (event) {
    event.preventDefault(); // 阻止链接的默认行为

    // 判断当前文本并切换
    // @ts-ignore
    if (languageLink.textContent.trim() === "Русский язык") {
      // @ts-ignore
      languageLink.textContent = "中文"; // 切换为中文
      // @ts-ignore
      languageLink.classList.add("chinese"); // 添加中文样式类
      globalLanguage.languageSuffix = "Ra"; // 更新全局语言后缀值为 'Ra'
    } else {
      // @ts-ignore
      languageLink.textContent = "Русский язык"; // 切换为俄语
      // @ts-ignore
      languageLink.classList.remove("chinese"); // 移除中文样式类
      // isChinese.value = true;
      globalLanguage.languageSuffix = "Cn"; // 更新全局语言后缀值为 'Ra'
    }
    language.value = globalLanguage.languageSuffix;
  });
});*/

// @ts-ignore
</script>
<style scoped>
.add-menu-container {
  position: absolute;
  right: 0;
  top: 100%; /* 根据实际的菜单栏高度调整 */
  z-index: 1000;
  background-color: #fff;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.fade-enter-active, .fade-leave-active {
  transition: opacity 0.5s;
}

.fade-enter, .fade-leave-to {
  opacity: 0;
}
</style>
